package com.srb.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.srb.oss.service.FileService;
import com.srb.oss.util.OssProperties;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT,
                OssProperties.KEY_ID, OssProperties.KEY_SECRET);

        //判断bucketName是否存在
        if (!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
            ossClient.createBucket(OssProperties.BUCKET_NAME);
            ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
        }

        // 创建PutObject请求。上传文件流
        //文件目录结构 "example/2022/07/15/uuid.jpg
        //构建日期路径
        String timeFolder = new DateTime().toString("/yyyy/MMdd/");
        //文件名生成
        fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
        String key = module + timeFolder +fileName;
        ossClient.putObject(OssProperties.BUCKET_NAME, key , inputStream);
        ossClient.shutdown();
        //https://srb-file-0714.oss-cn-shanghai.aliyuncs.com/exampledir/exampleobject.txt
        return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" +key;
    }

    @Override
    public void removeFile(String url) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OssProperties.ENDPOINT,
                OssProperties.KEY_ID, OssProperties.KEY_SECRET);

        //文件完整路径
        String host = "https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/";
//        String objectName = StringUtils.substringAfter(url,host);
        String objectName = url.substring(host.length());

        //删除文件或目录
        ossClient.deleteObject(OssProperties.BUCKET_NAME,objectName);

        ossClient.shutdown();
    }
}
